package token

import (
	"time"

	"kratos-layout/pkg/jwt/claim"

	"github.com/golang-jwt/jwt/v4"
)

type JWTTokenGen struct {
	secretKey []byte
	issuer    string
	nowFunc   func() time.Time
}

func NewJWTTokenGen(secretKey string, issuer string) *JWTTokenGen {
	return &JWTTokenGen{
		secretKey: []byte(secretKey),
		issuer:    issuer,
		nowFunc:   time.Now,
	}
}

func (j *JWTTokenGen) GenerateToken(userID int, expire time.Duration) (string, error) {
	nowSec := j.nowFunc()
	claims := jwt.NewWithClaims(jwt.SigningMethodHS256, &claim.CustomClaims{
		RegisteredClaims: jwt.RegisteredClaims{
			Issuer:    j.issuer,
			IssuedAt:  jwt.NewNumericDate(nowSec),
			ExpiresAt: jwt.NewNumericDate(nowSec.Add(expire)),
		},
		UserId: userID,
	})
	return claims.SignedString(j.secretKey)
}
